package cn.highset.modules.base.serviceimpl;

import cn.highset.common.vo.SearchVo;
import cn.highset.modules.base.dao.VoteItemDao;
import cn.highset.modules.base.entity.VoteItem;
import cn.highset.modules.base.service.VoteItemService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 投票活动明细接口实现
 *
 * @author Victor
 */
@Slf4j
@Service
@Transactional
public class VoteItemServiceImpl implements VoteItemService {

    @Autowired
    private VoteItemDao voteItemDao;

    @Override
    public VoteItemDao getRepository() {
        return voteItemDao;
    }

    @Override
    public Page<VoteItem> findByCondition(VoteItem voteItem, SearchVo searchVo, Pageable pageable) {

        return voteItemDao.findAll(new Specification<VoteItem>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<VoteItem> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");

                List<Predicate> list = new ArrayList<Predicate>();
                if (StrUtil.isNotBlank(voteItem.getVoteId())) {
                    list.add(cb.equal(root.get("voteId"), voteItem.getVoteId()));
                }
                //模糊搜素
                if (StrUtil.isNotBlank(voteItem.getDevelopUnit())) {
                    list.add(cb.like(root.get("developUnit"), '%' + voteItem.getDevelopUnit() + '%'));
                }
                //模糊搜素
                if (StrUtil.isNotBlank(voteItem.getStandNo())) {
                    list.add(cb.like(root.get("standNo"), '%' + voteItem.getStandNo() + '%'));
                }
                //模糊搜素
                if (StrUtil.isNotBlank(voteItem.getEquipmentName())) {
                    list.add(cb.like(root.get("equipmentName"), '%' + voteItem.getEquipmentName() + '%'));
                }
                //创建时间
                if (StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }
}
